package org.bycloud.security.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.bycloud.common.TreeNode;

public abstract class TreeNodeService<T> {

    protected abstract TreeNode toNode(T entity, Boolean checked);

    private boolean isRootNode(TreeNode node) {
        return StringUtils.equals(node.pid, "0");
    }

    protected List<TreeNode> toNodes(List<T> entitys, Boolean checked) {
        List<TreeNode> r = new ArrayList<TreeNode>();
        for (T t : entitys) {
            r.add(toNode(t, checked));
        }
        return r;
    }

    protected List<TreeNode> getTree(List<T> entitys, Boolean checked) {
        List<TreeNode> roots = new ArrayList<TreeNode>();
        List<TreeNode> nodes = toNodes(entitys, checked);
        for (TreeNode node : nodes) {
            if (this.isRootNode(node)) {
                node.children = getChildren(node.id, nodes);
                roots.add(node);
            }
        }
        return roots;
    }

    protected List<TreeNode> getChildren(String id, List<TreeNode> rootNodes) {
        List<TreeNode> children = new ArrayList<TreeNode>();

        for (TreeNode node : rootNodes) {
            if (StringUtils.isNotBlank(node.pid)) {
                if (node.pid.equals(id)) {
                    children.add(node);
                    node.children = getChildren(node.id, rootNodes);
                }
            }
        }
        return children;
    }

}
